package com.lizemin.websocketclient.config;

import com.lizemin.websocketclient.handler.SimpleWebSocketClientHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;

/**
 * WebSocket客户端配置
 *
 * @author lizemin
 * @version 1.0
 */
@Configuration
public class WebSocketClientConfig {

    @Value("${websocket.server.address}")
    private String serverAddress;

    /**
     * 创建WebSocket客户端
     *
     * @return WebSocket客户端
     */
    @Bean
    public WebSocketClient webSocketClient() {
        return new StandardWebSocketClient();
    }

    /**
     * 创建WebSocket处理器
     *
     * @return WebSocket处理器, 用于处理WebSocket事件
     */
    @Bean
    public SimpleWebSocketClientHandler simpleWebSocketClientHandler() {
        return new SimpleWebSocketClientHandler();
    }

    /**
     * WebSocket连接管理器，用于管理WebSocket连接
     *
     * @param webSocketClient WebSocket客户端
     * @param handler         WebSocket处理器
     * @return WebSocket连接管理器
     */
    @Bean
    public WebSocketConnectionManager webSocketConnectionManager(WebSocketClient webSocketClient, SimpleWebSocketClientHandler handler) {
        WebSocketConnectionManager manager = new WebSocketConnectionManager(
                webSocketClient,
                handler,
                serverAddress
        );
        // 项目启动时自动建立WebSocket连接
        manager.setAutoStartup(true);
        return manager;
    }

}